<template>
  <el-dialog :fullscreen="true"
             :close-on-click-modal="false"
             :visible="isVisible"
             :title="gridTitle"
             @close="handleCloseDialog"
             @open="handleOpenDialog"
             class="dialog_con">
    <section class="acceptance_dialog">
      <el-row>
        <el-col :span="10" class="leftForm">
          <el-form ref="form" :model="form" :rules="rules" label-width="88px">
            <el-row>
              <el-col :span="24">
                <el-form-item label="围栏名称" prop="name">
                  <el-input ref="wlname" v-model="form.name" placeholder="请输入围栏名称"/>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="地图范围" prop="mapRange">
                  <div style="width:calc(100% - 170px);margin-right: 8px;display:inline-block;">
                    <el-input v-show="false" v-model="form.mapRange" type="textarea" :required="true" :disabled="true"></el-input>
                  </div>
                  <el-button @click="draw" type="primary" size="medium">绘制</el-button>
                  <el-button @click="handClearGrid" size="medium">清空</el-button>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="是否显示" prop="isShow">
                  <el-switch
                    v-model="form.isShow"
                    active-value="0"
                    inactive-value="1">
                  </el-switch>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-container>
                  <el-header class="e-header">
                    <span>指定船舶</span>
                    <el-button @click="opendOperation('boat')" type="success" size="medium">选择</el-button>
                    <el-button @click="handClearIds('boat')" type="info" size="medium">清空</el-button>
                  </el-header>
                  <el-main>
                    <el-table v-loading="loading1" :data="tableData1" @selection-change="handleSelectionChange" border>
<!--                      <el-table-column type="selection" width="55" align="center"/>-->
                      <el-table-column label="序号" type="index" width="100" align="center">
                        <template slot-scope="scope">
                          <span>{{ scope.$index + 1}}</span>
                        </template>
                      </el-table-column>
                      <el-table-column label="船舶名称" align="center" prop="shipName"/>
                    </el-table>
                  </el-main>
                </el-container>
              </el-col>
              <el-col :span="24">
                <el-container>
                  <el-header class="e-header">
                    <span>指定人员</span>
                    <el-button @click="opendOperation('user')" type="success" size="medium">选择</el-button>
                    <el-button @click="handClearIds('user')" type="info" size="medium">清空</el-button>
                  </el-header>
                  <el-main>
                    <el-table v-loading="loading2" :data="tableData2" @selection-change="handleSelectionChange" border>
<!--                      <el-table-column type="selection" width="55" align="center"/>-->
                      <el-table-column label="序号" type="index" width="100" align="center">
                        <template slot-scope="scope">
                          <span>{{ scope.$index + 1}}</span>
                        </template>
                      </el-table-column>
                      <el-table-column label="人员名字" align="center" prop="name"/>
                    </el-table>
                  </el-main>
                </el-container>
              </el-col>
              <el-col :span="24">
                <el-container>
                  <el-header class="e-header">
                    <span>指定车辆</span>
                    <el-button @click="opendOperation('car')" type="success" size="medium">选择</el-button>
                    <el-button @click="handClearIds('car')" type="info" size="medium">清空</el-button>
                  </el-header>
                  <el-main>
                    <el-table v-loading="loading3" :data="tableData3" @selection-change="handleSelectionChange" border>
<!--                      <el-table-column type="selection" width="55" align="center"/>-->
                      <el-table-column label="序号" type="index" width="100" align="center">
                        <template slot-scope="scope">
                          <span>{{ scope.$index + 1}}</span>
                        </template>
                      </el-table-column>
                      <el-table-column label="车牌号" align="center" prop="name"/>
                    </el-table>
                  </el-main>
                </el-container>
              </el-col>
            </el-row>
          </el-form>
        </el-col>
        <el-col :span="14">
          <!-- 地图展示 -->
          <common-map ref="map2"
                      class="bottomMap"
                      :wms-ids="wmsIds"
                      :wms-grid-data="wmsGridData">
          </common-map>
        </el-col>
      </el-row>
    </section>
    <section slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="handleCloseDialog">取 消</el-button>
    </section>
    <operation-list
      :isShowShip="isShowShip"
      @closeDialog="closedOperation('boat')"
      :collected1.sync="form.shipIds"
      @ListSel="handleBoatList"
    >
    </operation-list>
    <app-user-list
      :isShowUser="isShowUser"
      @closeDialog="closedOperation('user')"
      :collected2.sync="form.userIds"
      @ListSel="handleUserList"
    >
    </app-user-list>
    <car-list
      :isShowCar="isShowCar"
      @closeDialog="closedOperation('car')"
      :collected3.sync="form.carIds"
      @ListSel="handleCarList"
    ></car-list>
  </el-dialog>
</template>

<script>
  import { TyDrawTool, TyDrawPolygon, TyFeatureLayer, TyMeasureTool } from '@/plugin/map/tyMapUtlis'
  import { Stroke, Style, Fill, Circle as CircleStyle } from 'ol/style'
  import { addFence, updateFence } from '@/api/basicInformation/fence'
  import WKT from 'ol/format/WKT'
  import operationList from './operationList'
  import appUserList from './appUserList'
  import carList from './carList'
  import { listFenceObject } from '@/api/basicInformation/fenceObject'

  export default {
    name: 'drawfence',
    components: {
      operationList,
      appUserList,
      carList
    },
    props: {
      isVisible: {
        type: Boolean,
        default: false
      },
      gridTitle: {
        type: String,
        default: ''
      },
      objectForm: {
        type: Object,
        default: {}
      },
      isAdd: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        map: null,
        mapOption: null,
        // 手工绘制工具
        drawTool: null,
        // 网格绘制工具
        drawPolygon: null,
        // 当前网格图层
        feature: null,
        isShowShip: false,
        isShowUser: false,
        isShowCar: false,
        wmsGridData: [],
        wmsIds: ['4403T_MAP_COMM_GRID.659'],
        form: {
          mapRange: '',
          theGeom: '',
          shipIds: '',
          userIds: '',
          carIds: '',
          isShow: '0'
        },
        rules: {
          name: [
            { required: true, message: '请填围栏名称', trigger: 'blur' },
            { min: 0, max: 200, message: '长度在 0 到 200 个字符', trigger: 'blur' }
          ],
          mapRange: [
            { required: true, message: '请绘制地图范围', trigger: 'change' }
          ]
        },
        collected1: {},
        tableData1: [],
        collected2: {},
        tableData2: [],
        collected3: {},
        tableData3: [],
        loading1: false,
        loading2: false,
        loading3: false,
        center: []
      }
    },
    watch: {
      objectForm: {
        handler(val) {
          const data = this.objectForm
          let poi = ''
          let pois = []
          if (!this.isAdd) {
            this.form = this.objectForm
            this.form.mapRange = data.mapRange
            this.form.theGeom = data.theGeom
            poi = data.theGeom.replace('POLYGON((', '').replace('POLYGON((', '))')
            pois = poi.split(',')
            this.center = pois[0].split(' ')
          } else {
            this.wmsIds = []
            this.wmsGridData = [] // [{ type: 'MultiPolygon', coordinates: [[[[]]]] }]
            this.form.mapRange = ''
            this.form.theGeom = ''
            this.form.shipIds = ''
            this.form.userIds = ''
            this.form.carIds = ''
          }
        }
      },
      collected1: {
        handler: function(val) {
          console.log('collected1===>', this.form.shipIds)
          this.form.shipIds += val[0]
          let that = this
          val[1].forEach(function(item) {
            that.tableData1.push(item)
          })
          this.$forceUpdate()
        }
      },
      collected2: {
        handler: function(val) {
          console.log('collected2===>', this.form.userIds)
          this.form.userIds += val[0]
          let that = this
          val[1].forEach(function(item) {
            that.tableData2.push(item)
          })
          this.$forceUpdate()
        }
      },
      collected3: {
        handler: function(val) {
          this.form.carIds += val[0]
          let that = this
          val[1].forEach(function(item) {
            that.tableData3.push(item)
          })
          this.$forceUpdate()
        }
      }
    },
    methods: {// 表单重置
      reset() {
        this.form = {
          name: '',
          mapRange: '',
          theGeom: '',
          shipIds: '',
          userIds: '',
          carIds: '',
          isShow: '0'
        }
        this.tableData1 = []
        this.tableData2 = []
        this.tableData3 = []
        this.resetForm('form')
        this.wmsIds = []
        this.wmsGridData = [] // [{ type: 'MultiPolygon', coordinates: [[[[]]]] }]
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.selection = selection
      },
      /**
       * @Author yuesheng.zhu@topevery.club
       * @Date 2019/5/10 15:51
       * @Description 初始化地图
       */
      initMap() {
        this.drawTool = new TyDrawTool(this.map.getMap(), new Style({
          fill: new Fill({
            color: 'rgba(255, 255, 255, 0.2)'
          }),
          stroke: new Stroke({
            color: '#ffcc33',
            width: 3
          }),
          image: new CircleStyle({
            radius: 7,
            fill: new Fill({
              color: '#ffcc33'
            })
          })
        }))
        this.mapOption = {
          map: this.map.getMap()
        }
        this.drawPolygon = new TyDrawPolygon(this.mapOption)
        if (this.measureTool === null) {
          this.measureTool = new TyMeasureTool(this.map.getMap())
        }
        if (this.featureLayer === null) {
          this.featureLayer = new TyFeatureLayer(this.mapOption)
        }
        if (this.form.mapRange !== '') {
          this.wmsIds = ['4403T_MAP_COMM_GRID.659']
          this.wmsGridData = [this.form.mapRange]
          this.map.getMap().updateSize()
          this.map.getMap().getView().animate({
            center: this.center,
            duration: 500
          })
        }
      },
      /**
       * @Author yuesheng.zhu@topevery.club
       * @Date 2019/5/10 15:52
       * @Description 绘制网格图层
       */
      draw() {
        if (this.form.name === '' || this.form.name === undefined || this.form.name === null) {
          this.$alert('请先输入围栏名称', '提示', {
            confirmButtonText: '确定'
          })
          this.$refs.wlname.focus()
          return
        }
        // this.closeFun()
        const value = 'Polygon'
        this.drawTool.start(value, (event) => {
          if (this.feature) {
            this.drawTool.clear()
          }
          this.feature = event.feature
          const format = new WKT()
          const lonlat = format.writeFeature(this.feature, {
            dataProjection: 'EPSG:4326',
            featureProjection: 'EPSG:4326'
          })
          this.feature.isCommit = false
          this.feature.gridType = 'T_MAP_UNIT_GRID' // 默认去掉网格类型
          let mapLines = []
          const xyList = this.feature.values_['geometry'].flatCoordinates
          xyList.forEach((item, index) => {
            if (index % 2 === 1) {
              mapLines.push([xyList[index - 1], xyList[index]])
            }
          })
          mapLines = [[mapLines]]
          this.wmsIds = ['4403T_MAP_COMM_GRID.659']
          this.wmsGridData = [{
            type: 'MultiPolygon',
            gridName: this.form.name,
            coordinates: mapLines,
            bsfBorderColor: this.form.bsfBorderColor,
            bsfFillColor: this.form.bsfFillColor
          }]
          this.form.mapRange = JSON.stringify({ type: 'MultiPolygon', gridName: this.form.name, coordinates: mapLines })
          console.log('this.form.mapRange=====>',this.form.mapRange)
          this.form.theGeom = lonlat
          // 绘制完成取消绘面
          setTimeout(() => {
            if (this.measureTool) {
              this.measureTool.close()
            }
          }, 50)
          // 绘制完成后切换为编辑
          setTimeout(() => {
            this.closeFun()
            this.drawPolygon.openSelect()
            this.drawPolygon.closeMultiSelect()
          }, 300)

          // this.drawPolygon.addPolygon(this.feature)
          // this.drawPolygon.initFocusFeatures()
        })
      },
      /**
       * @author：yi.zhou@topevery.cn
       * @Description 清空责任网格
       */
      handClearGrid() {
        this.wmsGridData = [{ type: 'MultiPolygon', coordinates: [[[[]]]] }]
        this.wmsIds = ['4403T_MAP_COMM_GRID.659']
        this.form.bsfFenceAcreage = ''
        this.form.mapRange = ''
        if (this.measureTool) {
          this.measureTool.close() // 清除绘面
        }
        this.$forceUpdate()
      },
      handClearIds($event) {
        this.$confirm('确定要清空吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(() => {
          switch ($event) {
            case 'boat':
              this.tableData1 = []
              this.form.shipIds = ''
              break
            case 'user':
              this.tableData2 = []
              this.form.userIds = ''
              break
            case 'car':
              this.tableData3 = []
              this.form.carIds = ''
              break
          }
          this.$forceUpdate()
        });

      },
      /**
       * @Author yuesheng.zhu@topevery.club
       * @Date 2019/5/10 16:29
       * @Description 关闭绘制网格/单选/多选/编辑
       */
      closeFun() {
        this.drawTool.close()
        this.drawPolygon.closeCute()
        this.drawPolygon.closeSelect()
        this.drawPolygon.closeMultiSelect()
        this.drawPolygon.closeEdit()
      },
      submitForm() {
        console.log(this.$refs['form'])
        this.$refs['form'].validate(valid => {
          if (valid) {
            // console.log(this.form.mapRange)
            // delete this.form.mapRange
            if (this.form.id != null) {
              updateFence(this.form).then(response => {
                this.msgSuccess('修改成功')
                this.$emit('closeDialog', true)
              })
            } else {
              addFence(this.form).then(response => {
                this.msgSuccess('新增成功')
                this.$emit('closeDialog', true)
              })
            }
          }
        })
      },
      /**
       * @author: mi.liu@topevery.club
       * @Date: 2019/7/9 10:12
       * @description: 关闭弹框之后
       */
      handleCloseDialog() {
        this.reset()
        this.$refs['form'].resetFields()
        this.$emit('closeDialog', false)
      },
      handleOpenDialog() {
        this.$nextTick(() => {
          this.map = this.$refs.map2.map
          this.initMap()
        })
        this.initSelect()
      },
      initSelect() {
        if (this.objectForm.id !== null && this.objectForm.id !== undefined) {
          const queryParams = {
            pageNum: 1,
            pageSize: 999999,
            shipName: undefined,
            shipCode: undefined,
            objectType: '3',
            electronicFenceId: this.objectForm.id
          }
          let list1 = '', list2 = '', list3 = '', that = this
          listFenceObject(queryParams).then(response1 => {
            response1.rows.forEach((item) => {
              let ta = {}
              ta.id = item.objectId
              ta.shipName = item.objectName
              that.tableData1.push(ta)
              list1 += item.objectId + ','
            })
            that.form.shipIds = list1
          })
          queryParams.objectType = '1'
          listFenceObject(queryParams).then(response1 => {
            response1.rows.forEach((item) => {
              let ta = {}
              ta.id = item.objectId
              ta.name = item.objectName
              that.tableData2.push(ta)
              list2 += item.objectId + ','
            })
            that.form.userIds = list2
          })
          queryParams.objectType = '2'
          listFenceObject(queryParams).then(response1 => {
            response1.rows.forEach((item) => {
              let ta = {}
              ta.id = item.objectId
              ta.name = item.objectName
              that.tableData3.push(ta)
              list3 += item.objectId + ','
            })
            that.form.carIds = list3
          })
        }
        else {
          this.tableData1 = []
          this.form.shipIds = ''
          this.tableData2 = []
          this.form.userIds = ''
          this.tableData3 = []
          this.form.carIds = ''
        }
      },
      opendOperation($event) {
        switch ($event) {
          case 'boat':
            this.isShowShip = true
            break
          case 'user':
            this.isShowUser = true
            break
          case 'car':
            this.isShowCar = true
            break
        }
      },
      closedOperation($event) {
        switch ($event) {
          case 'boat':
            this.isShowShip = false
            break
          case 'user':
            this.isShowUser = false
            break
          case 'car':
            this.isShowCar = false
            break
        }
      },
      handleBoatList(data) {
        this.collected1 = data
        this.isShowShip = false
      },
      handleUserList(data) {
        this.collected2 = data
        this.isShowUser = false
      },
      handleCarList(data) {
        this.collected3 = data
        this.isShowCar = false
      }
    }
  }
</script>
<style lang="scss" scoped>
  .dialog_con {
    .leftForm {
      padding: 20px;
      overflow: auto;
      height: calc(100vh - 108px);

      ::v-deep .el-table {
        height: 200px;
      }

      ::v-deep .el-table__body-wrapper {
        height: calc(100% - 44px);
        overflow-y: auto;
      }
    }

    ::v-deep .el-dialog__body {
      padding: 0;
    }

    ::v-deep .el-dialog__header {
      padding: 10px 20px 10px;
      background-color: #f2f2f2;

      .el-dialog__headerbtn {
        top: 12px;
      }
    }

    ::v-deep .el-dialog__footer {
      text-align: center;
      position: absolute;
      left: 0;
      right: 0;
      bottom: 0;
      padding: 15px;
      background: #f1f1f1;
    }

    .bottomMap {
      height: calc(100vh - 108px);
      overflow-y: auto;
    }

  }
</style>
<style>
  .el-header, .el-footer {
    background-color: #B3C0D1;
    color: #333;
    text-align: center;
    line-height: 60px;
    font-size: 18px;
    font-weight: bold;
  }

  .el-main {
    padding: 0;
  }
</style>
